<?php
/**
 *   This file is part of GeoArticle (a Joomla plugin).
 *   Written by Ivar Bergman (www.ivarbergman.se)
 *   Copyright (c) 2010 Ivar Bergman. All rights reserved.
 *
 *   GeoArticle is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   GeoArticle is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with GeoArticle.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.view');

class GeoArticleViewArticleTags extends JView
{

  function display($tpl = null)
  {
    global $mainframe;

    $this->addTemplatePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'views'.DS.'articletags'.DS.'tmpl');

    switch($this->getLayout()) {
    case 'save_tags':
      $this->_saveTags($tpl);
      break;
    case 'tags':
      $this->_tagsForm($tpl);
      break;
    }

    parent::display($tpl);
  }
  
  function _saveTags($tpl) {
    // Check for request forgeries
    JRequest::checkToken() or jexit( 'Invalid Token' );
    
    $a_errors = array();
    
    $db  =& JFactory::getDBO();

    $cid = JRequest::getVar('cid', 0, '', 'int');
    $user = JFactory::getUser();

    $a_gaids = JRequest::getVar( 'associations', array(), 'post', 'array' );
    $a_gaids = array_keys($a_gaids);

    $long = JRequest::getVar('long', 0, '', 'double');
    $lat = JRequest::getVar('lat', 0, '', 'double');
    $phone  = JRequest::getVar('phone', 0, '', 'string');
    $email      = JRequest::getVar('email', 0, '', 'string');
    $web        = JRequest::getVar('web', 0, '', 'string');
    $street     = JRequest::getVar('street', 0, '', 'string');
    $postal     = JRequest::getVar('postal', 0, '', 'string');
    $city       = JRequest::getVar('city', 0, '', 'string');
    $country    = JRequest::getVar('country', 0, '', 'string');

    // Now remove existing, invalid associations
    $db->setQuery( 
		  sprintf(
			  'DELETE FROM #__content_geoarticle WHERE cid = %d %s',
			  $cid,
			  (count($a_gaids)) ? sprintf('AND gaid NOT IN ( %s )', implode( ',', $a_gaids )) : ''
			  )
		   );

    if (!$db->query()) {
      $a_errors[] = $this->setError($db->getErrorMsg());
      return;
    }


    // Set the GeoTag values
    $db->setQuery( 
		  sprintf(
			  'REPLACE INTO #__content_geoarticle_geo SET cid=%d, `long`=%f, lat=%f, phone="%s", email="%s", web="%s", street="%s", postal="%s", city="%s", country="%s"',
			  (int) $cid,
			  (double) $long,
			  (double) $lat,
			  (string) $phone,
			  (string) $email,
			  (string) $web,
			  (string) $street,
			  (string) $postal,
			  (string) $city,
			  (string) $country
			  )
		   );

    if (!$db->query()) {
      $a_errors[] = $this->setError($db->getErrorMsg());
      echo $db->getErrorMsg();
      exit();
      return;
    }
    
    // Now let's find the tags we need to insert associations for:
    if (count($a_gaids) > 0) {
      $db->setQuery( 
		    sprintf(
			    'SELECT b.id AS gaid FROM #__geoarticle AS b'.
			    ' LEFT JOIN #__content_geoarticle AS cb ON (cb.gaid = b.id AND cb.cid = %d)'.
			    ' WHERE cb.gaid IS NULL AND b.id IN (%s)',
			    $cid,
			    implode( ',', $a_gaids )
			    )
		     );

      $new_associations = $db->loadObjectList();

      if ($db->getErrorNum())
	$a_errors[] = 'Error while fetching existing article associations from database: '.$db->getErrorMsg();
      else
	foreach ($new_associations as $new_ass) {
	  $db->setQuery( 
			sprintf(
				'INSERT INTO #__content_geoarticle (gaid, cid, created_by) VALUES (%d,%d,%d)',
				(int) $new_ass->gaid,
				(int) $cid,
				(int) $user->id
				)
			 );

	  if (!$db->query()) {
	    $a_errors[] = $this->setError($db->getErrorMsg());
	    return;
	  }
	}
    }
    $this->assignRef('errors', $a_errors);
    
  }

  function _tagsForm($tpl) {
    global $mainframe, $option;

    $a_errors = array();

    $db  =& JFactory::getDBO();
    $uri =& JFactory::getURI();

    $cid = JRequest::getVar('cid', 0, '', 'int');

    // First let;s find all avalable the tags:    
    $tags = array();
    
    // First get the tags:
    $db->setQuery( 
		  'SELECT id, title FROM #__geoarticle ORDER BY ordering ASC, title ASC'
		   );
    $tags = $db->loadObjectList();

    if ($db->getErrorNum())
      $a_errors[] = 'Error while fetching tags from database: '.$db->getErrorMsg();
      

    // Second get the geo info:
    $db->setQuery( 
      sprintf(
	 'SELECT cid, `long`, lat,phone,email,web,street,postal,city,country  FROM #__content_geoarticle_geo WHERE cid=%d',
	 $cid
	      )
    );
    $geo = $db->loadObject();
    if ($db->getErrorNum())
      $a_errors[] = 'Error while fetching tags from database: '.$db->getErrorMsg();
      

    // Now find the associations:
    $associations = array();
    $db->setQuery( 
		  sprintf(
			  'SELECT gaid FROM #__content_geoarticle WHERE cid = %d',
			  $cid
			  )
		   );
    $cid_gaids = $db->loadObjectList();
    
    if ($db->getErrorNum())
      $a_errors[] = 'Error while fetching article associations from database: '.$db->getErrorMsg();
    else
      foreach ($cid_gaids as $association)
      	$associations[] = (int) $association->gaid;

    // Assign to the template
    $this->assignRef('cid', $cid );
    $this->assignRef('long', $geo->long );
    $this->assignRef('lat', $geo->lat );
    $this->assignRef('phone', $geo->phone );
    $this->assignRef('email', $geo->email );
    $this->assignRef('web', $geo->web );
    $this->assignRef('street', $geo->street );
    $this->assignRef('postal', $geo->postal );
    $this->assignRef('city', $geo->city );
    $this->assignRef('country', $geo->country );
    $this->assignRef('tags', $tags );
    $this->assignRef('associations', $associations );
    $this->assignRef('user', JFactory::getUser());
    $this->assignRef('errors', $a_errors);

    return;
  }

}
